package _mst;

import _object.ListNode;

/**
 * 面试题 02.05. 链表求和
 */
public class T0205 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l0 = new ListNode(-1), dummy = l0;
        boolean flag = false;
        while (l1 != null && l2 != null) {
            int curSum = l1.val + l2.val + (flag ? 1 : 0);
            l0.next = new ListNode(curSum % 10);
            flag = curSum >= 10;
            l0 = l0.next;
            l1 = l1.next;
            l2 = l2.next;
        }
        l0.next = l1 != null ? l1 : l2;
        if (flag) {
            while (l0.next != null) {
                int curSum = l0.next.val + (flag ? 1 : 0);
                l0.next.val = curSum % 10;
                flag = curSum >= 10;
                l0 = l0.next;
            }
            if (flag) l0.next = new ListNode(1);
        }
        return dummy.next;
    }
}
